<template>
  <div class="app-container">
    <div style="padding: 20px;">
      <el-row>
        <el-col :span="4">
          <strong style="font-size: 20px;">
            新增/修改
          </strong>
        </el-col>
      </el-row>

      <div style="padding:20px">
        <el-form ref="form" :model="form" :rules="rules" label-width="150px">
          <el-form-item label="用户名">
            <el-input v-model="form.username" :disabled="true" />
          </el-form-item>
          <el-form-item label="电话" prop="phone">
            <el-input v-model="form.phone" />
          </el-form-item>
          <el-form-item label="名称" prop="name">
            <el-input v-model="form.name" />
          </el-form-item>
          <el-form-item label="小队" prop="squad">
            <el-select
              v-model="form.squad"
              filterable
              clearable
              @change="$forceUpdate()"
            >
              <el-option
                v-for="item in squads"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="角色" prop="role">
            <el-select
              v-model="form.role"
              filterable
              clearable
              @change="$forceUpdate()"
            >
              <el-option
                v-for="item in roles"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="可选角色" prop="role">
            <el-checkbox-group
              v-model="form.roles"
            >
              <el-checkbox v-for="item in roles" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="代收账号">
            <el-select
              v-model="form.collector"
              filterable
              clearable
              @change="$forceUpdate()"
            >
              <el-option
                v-for="item in staffs"
                :key="item.id"
                :label="item.name + '(' + item.phone + ')'"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="身高">
            <el-input-number v-model="form.height" />
            <div class="help-text" style="display: flex;">
              <div>
                <p class="el-icon-info" />
              </div>
              <div>
                <p v-html="'单位CM'" />
              </div>
            </div>
          </el-form-item>
          <el-form-item label="体重">
            <el-select
              v-model="form.weightType"
              filterable
              clearable
              @change="$forceUpdate()"
            >
              <el-option
                v-for="item in weightTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="年龄">
            <el-select
              v-model="form.age"
              filterable
              clearable
              @change="$forceUpdate()"
            >
              <el-option
                v-for="item in ageOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="综合评级">
            <el-select
              v-model="form.evaluation"
              filterable
              clearable
              @change="$forceUpdate()"
            >
              <el-option
                v-for="item in evaluationOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="是否下单">
            <el-checkbox v-model="form.canMakeOrder" />
          </el-form-item>
          <el-form-item label="是否在职">
            <el-checkbox v-model="form.enabled" />
          </el-form-item>
          <el-form-item label="场所管理">
            <el-checkbox v-model="form.isManager" />
            <div class="help-text" style="display: flex;">
              <div>
                <p class="el-icon-info" />
              </div>
              <div>
                <p v-html="'设置为经理之后，用户在小程序可以操作门店所有数据'" />
              </div>
            </div>
          </el-form-item>
          <!-- 经理二级权限 -->
          <div v-if="form.isManager == true">
            <el-divider>经理二级权限</el-divider>
            <el-form-item label="不查看总报表">
              <el-checkbox v-model="form.extraData.noStatistics" />
              <div style="color:#909399;font-size:12px;">针对经理级权限，设置了就不能看前端数据汇总</div>
            </el-form-item>
            <el-form-item label="修改权限">
              <el-checkbox v-model="form.extraData.edit" />
              <div style="color:#909399;font-size:12px;">修改员工权限，不设置就不能修改</div>
            </el-form-item>
            <div v-if="form.extraData.edit == true">
              <el-form-item label="禁止修改小队">
                <el-checkbox v-model="form.extraData.noChangeSquad" />
                <div style="color:#909399;font-size:12px;">挂钩修改权限，开通修改权限默认可以修改员工小队</div>
              </el-form-item>
              <el-form-item label="禁止修改角色">
                <el-checkbox v-model="form.extraData.noChangeRole" />
                <div style="color:#909399;font-size:12px;">挂钩修改权限，开通修改权限默认可以修改员工角色</div>
              </el-form-item>
            </div>
            <el-form-item label="操作分账">
              <el-checkbox v-model="form.extraData.canExecuteSettle" />
              <div style="color:#909399;font-size:12px;">针对经理级权限，设置了小程序可以看未分账订单并进行分账</div>
            </el-form-item>
          </div>

          <el-divider>队长/经纪级次权限</el-divider>
          <el-form-item label="可修改角色">
            <el-checkbox v-model="form.extraData.changeRoule" />
            <div style="color:#909399;font-size:12px;">针对队长/经纪可修改下面员工角色权限，不设置就不能修改</div>
          </el-form-item>
          <el-form-item label="可执行扣罚">
            <el-checkbox v-model="form.extraData.canPenaltie" />
          </el-form-item>

          <el-divider>员工权限</el-divider>
          <el-form-item label="下单是否需要打卡">
            <el-checkbox v-model="form.extraData.attendanceOrder" />
            <div style="color:#909399;font-size:12px;">挂钩修改权限，就打卡才能下单</div>
          </el-form-item>
          <el-form-item label="禁止取消订单">
            <el-checkbox v-model="form.extraData.noCancelOrder" />
            <div style="color:#909399;font-size:12px;">禁止了的账号，不能取消订单，包括自己的订单</div>
          </el-form-item>
          <el-form-item label="房间公主">
            <el-checkbox v-model="form.extraData.isPrincess" />
            <div style="color:#909399;font-size:12px;">设置了房间公主，扫台面码会跳转到房间操作界面</div>
          </el-form-item>
          <el-form-item label="查看所有结算订单">
            <el-checkbox v-model="form.extraData.isCashier" />
            <div style="color:#909399;font-size:12px;">设置了查看所有结算订单，小程序的挂账订单就可以查看全部并统收，否则只能看自己有权限看的员工的挂账订单</div>
          </el-form-item>
          <el-form-item label="统收订单">
            <el-checkbox v-model="form.extraData.canCashier" />
            <div style="color:#909399;font-size:12px;">设置了统收订单，就可以查看有自己订单的房间所有的订单，可以对小程序的挂账订单进行统收，否则，只可以查看以及收自己的订单</div>
          </el-form-item>
          <el-form-item label="小程序订房">
            <el-checkbox v-model="form.extraData.isBooker" />
            <div style="color:#909399;font-size:12px;">设置了小程序订房，小程序就可以进行开台以及结台操作</div>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">保存</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      id: Number(this.$route.params.id),
      form: {
        username: '',
        squad: null,
        name: '',
        role: null,
        collector: null,
        phone: '',
        height: 0,
        weightType: 0,
        age: 0,
        evaluation: 0,
        canMakeOrder: false,
        isManager: false,
        enabled: true,
        roles: [],
        extraData: {
          isPrincess: false,
          isBooker: false,
          isCashier: false,
          canCashier: false,
          noStatistics: false,
          changeRoule: false,
          edit: false,
          canPenaltie: false,
          noCancelOrder: false,
          noChangeSquad: false,
          noChangeRole: false,
          attendanceOrder: false,
          canExecuteSettle: false
        }
      },
      rules: {
        name: [
          { required: true }
        ],
        role: [
          { required: true }
        ],
        phone: [
          { required: true }
        ]
      },
      staffs: [],
      squads: [],
      roles: [],
      weightTypeOptions: [
        { label: '苗条', value: 0 },
        { label: '匀称', value: 1 },
        { label: '丰满', value: 2 }
      ],
      ageOptions: [
        { label: '18-20岁', value: 0 },
        { label: '21-23岁', value: 1 },
        { label: '24-26岁', value: 2 }
      ],
      evaluationOptions: [
        { label: '素人 ★☆☆', value: 0 },
        { label: '模特 ★★☆', value: 1 },
        { label: '名媛 ★★★', value: 2 }
      ]
    }
  },
  created() {
    if (this.id) {
      this.axios.get(`/officer/staffs/${this.id}`, { params: {
        '@expands': `['entity.user']`
      }}).then((res) => {
        this.form.username = res.data.user?.__metadata.username
        this.form.squad = res.data.squad?.id
        this.form.name = res.data.name
        this.form.role = res.data.role?.id
        this.form.collector = res.data.collector?.id
        this.form.phone = res.data.phone
        this.form.height = res.data.height
        this.form.weightType = res.data.weightType
        this.form.age = res.data.age
        this.form.evaluation = res.data.evaluation
        this.form.canMakeOrder = res.data.canMakeOrder
        this.form.isManager = res.data.isManager
        this.form.enabled = res.data.enabled
        if (res.data.roles != null) { this.form.roles = res.data.roles }
        if (typeof (res.data.extraData.isPrincess) !== 'undefined') {
          this.form.extraData.isPrincess = res.data.extraData.isPrincess
        } else {
          this.form.extraData.isPrincess = false
        }
        if (typeof (res.data.extraData.isBooker) !== 'undefined') {
          this.form.extraData.isBooker = res.data.extraData.isBooker
        } else {
          this.form.extraData.isBooker = false
        }
        if (typeof (res.data.extraData.attendanceOrder) !== 'undefined') {
          this.form.extraData.attendanceOrder = res.data.extraData.attendanceOrder
        } else {
          this.form.extraData.noStatistics = false
        }
        if (typeof (res.data.extraData.changeRoule) !== 'undefined') {
          this.form.extraData.changeRoule = res.data.extraData.changeRoule
        } else {
          this.form.extraData.changeRoule = false
        }
        if (typeof (res.data.extraData.edit) !== 'undefined') {
          this.form.extraData.edit = res.data.extraData.edit
        } else {
          this.form.extraData.edit = false
        }
        if (typeof (res.data.extraData.noCancelOrder) !== 'undefined') {
          this.form.extraData.noCancelOrder = res.data.extraData.noCancelOrder
        } else {
          this.form.extraData.noCancelOrder = false
        }
        if (typeof (res.data.extraData.isCashier) !== 'undefined') {
          this.form.extraData.isCashier = res.data.extraData.isCashier
        } else {
          this.form.extraData.isCashier = false
        }
        if (typeof (res.data.extraData.canCashier) !== 'undefined') {
          this.form.extraData.canCashier = res.data.extraData.canCashier
        } else {
          this.form.extraData.canCashier = false
        }
        if (typeof (res.data.extraData.canPenaltie) !== 'undefined') {
          this.form.extraData.canPenaltie = res.data.extraData.canPenaltie
        } else {
          this.form.extraData.canPenaltie = false
        }
        if (typeof (res.data.extraData.noChangeSquad) !== 'undefined') {
          this.form.extraData.noChangeSquad = res.data.extraData.noChangeSquad
        } else {
          this.form.extraData.noChangeSquad = false
        }
        if (typeof (res.data.extraData.noChangeRole) !== 'undefined') {
          this.form.extraData.noChangeRole = res.data.extraData.noChangeRole
        } else {
          this.form.extraData.noChangeRole = false
        }
        if (typeof (res.data.extraData.canExecuteSettle) !== 'undefined') {
          this.form.extraData.canExecuteSettle = res.data.extraData.canExecuteSettle
        } else {
          this.form.extraData.canExecuteSettle = false
        }
      })
    }
    this.getSquads()
    this.getRoles()
    this.getStaffs()
  },
  methods: {
    getStaffs() {
      this.axios.get(`/officer/staffs`, {
        params: {
          limit: 10000000
        }
      }).then((res) => {
        this.staffs = res.data
      })
    },
    getSquads() {
      this.axios.get(`/officer/squads`, {
        params: {
          limit: 10000000
        }
      }).then((res) => {
        this.squads = res.data
      })
    },
    getRoles() {
      this.axios.get(`/officer/roles`, {
        params: {
          limit: 10000000
        }
      }).then((res) => {
        this.roles = res.data
      })
    },
    cleanBlankAttributes(data) {
      for (var propName in data) {
        if (data[propName] === null || data[propName] === undefined) {
          delete data[propName]
        }
      }
    },
    onSubmit() {
      if (!this.form.name) {
        this.$message.error('请填写名称！')
        return
      }
      if (!this.form.phone) {
        this.$message.error('请填写电话！')
        return
      }
      if (!this.form.role) {
        this.$message.error('请选择角色！')
        return
      }
      if (this.id) {
        const loading = this.$loading({
          lock: true,
          text: '数据交互中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        this.axios.put(`/officer/staffs/${this.id}`, this.form).then((res) => {
          this.$message.success('修改成功！')
          this.$router.go(-1)
          loading.close()
        })
      } else {
        const loading = this.$loading({
          lock: true,
          text: '数据交互中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        this.axios.get(`/officer/users`, { params: {
          '@filter': `entity.getUsername() == "${this.form.phone}"`,
          '@expands': '["entity.staffs"]'
        }}).then((res) => {
          if (res.data.length > 0) {
            const user = res.data[0]
            if (!user.enabled) {
              loading.close()
              this.$message.error('此电话用户名账号已停用！')
              return
            }
            const storeStaff = user.staffs.find(v => v.__metadata.store.id === parseFloat(this.store))
            if (storeStaff) {
              loading.close()
              this.$message.error('此电话用户名在改门店已建立员工信息！')
              return
            }
            const form = JSON.parse(JSON.stringify(this.form))
            form.user = user.id
            this.cleanBlankAttributes(form)
            this.axios.post(`/officer/staffs`, form).then(staff => {
              loading.close()
              this.$message.success('修改成功！')
              this.$router.go(-1)
            })
          } else {
            this.axios.post(`/officer/users`, {
              username: this.form.phone,
              email: this.form.phone + '@email.com',
              enabled: true,
              plainPassword: 'nightkeeper'
            }).then(user => {
              this.form.user = user.data.id
              this.axios.post(`/officer/staffs`, this.form).then(staff => {
                loading.close()
                this.$message.success('修改成功！')
                this.$router.go(-1)
              })
            })
          }
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.help-text {
  display: flex;
  p {
    color: gray;
    line-height: 1.3em;
  }
  div {
    padding: 0 3px;
  }
}
</style>
